<template>
  <div class="users">
    <base-template :breadList="['用户管理', '用户列表']">
      <el-row class="users_header" type="flex" justify="space-between">
        <div class="users_left">
          <el-input class="search" v-model="paginationInfo.query" @change='searchUsers'  @clear='searchUsers' clearable :autofocus="true"></el-input>
          <el-button class="search el-icon-search" @click='searchUsers'></el-button>
        </div>
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-row>
      <!-- 表格 -->
      <el-table :data="usersData" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户" > </el-table-column>
        <el-table-column prop="role_name" label="角色权限" width="140"> </el-table-column>
        <el-table-column prop="mobile" label="手机" width="150"> </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template v-slot="scope">
            {{ new Date(scope.row.create_time).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="80">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeState(scope.row)"> </el-switch>
          </template> </el-table-column
        ><el-table-column prop="email" label="邮箱"> </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="paginationInfo.pagesize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" :before-close="handleClose">
        <el-form :model="addForm" status-icon :rules="addRules" ref="addForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="giveUpAdd">取 消</el-button>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
        </span>
      </el-dialog>
    </base-template>
  </div>
</template>

<script>
import BaseTemplate from '../../component/base-template.vue'
export default {
  components: {
    BaseTemplate,
  },
  data() {
    const checkEmail = (rule, value, callback) => {
      const val = value.trim()
      if (!val) {
        callback()
      } else {
        const reg = /^\w+([-+.]?\w+)@\w+([-.]\w+).\w+([-.]\w+)*$/
        if (reg.test(val)) {
          callback()
        } else {
          callback(new Error('邮箱格式填写有误'))
        }
      }
    }
    const checkMobile = (rule, value, callback) => {
      const val = String(value).trim()
      if (!val) {
        callback()
      } else {
        const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('手机格式填写有误'))
        }
      }
    }
    return {
      usersData: [],
      paginationInfo: {
        query:'',
        pagenum: 1, // 当前页
        pagesize: 5, //每页多少条数据
      },
      total: 0, //总计条数
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 14, message: '请输入5-14位用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6-16位密码', trigger: 'blur' },
        ],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getUsersData()
  },
  methods: {
    getUsersData() {
      this.$store
        .dispatch('getRequest', { path: '/users', params: this.paginationInfo })
        .then((res) => {
          this.total = res.total
          this.usersData = res.users
        })
        .catch(() => {})
    },
    handleSizeChange(val) {
      this.paginationInfo.pagesize = val
      this.getUsersData()
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.paginationInfo.pagenum = val
      this.getUsersData()
      // console.log(`当前页: ${val}`)
    },
    changeState(row) {
      this.$store
        .dispatch('putRequest', { path: `/users/${row.id}/state/${row.mg_state}` })
        .then(() => {
          this.$message.success('修改状态成功')
        })
        .catch((res) => {
          this.$message.error(res)
        })
    },

    // 添加用户区域
    giveUpAdd() {
      this.$refs.addForm.resetFields()
      this.addDialogVisible = false
    },
    submitAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$store
            .dispatch('postRequest', { path: '/users', params: this.addForm })
            .then(() => {
              this.giveUpAdd()
              this.$message.success('添加用户成功')
            })
            .catch((res) => {
              this.$message.error(res)
            })
        }
      })
    },
    handleClose(done) {
      //关闭dialog
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
          this.giveUpAdd()
        })
        .catch((_) => {})
    },

    // 查询
    searchUsers(){
      this.paginationInfo.pagenum=1
      this.$store.dispatch('getRequest',{path:'/users',params:this.paginationInfo}).then(res=>{
        this.usersData=res.users
        this.total=res.total
        // console.log(res);
      })

    }
  },
}
</script>

<style lang="less" scoped>
.el-row.users_header {
  display: flex;
  justify-content: space-between;
}
</style>
